package handlers

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"secure-sys/cache"
	"secure-sys/models"
	"secure-sys/pkg"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_login_key := "login_error_" + username
	errorConfig, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errorConfig >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errorConfig == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "密码错误三次",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录游戏",
		})
		return
	}
}
func UserAddRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))

	data := models.UserRole{
		Uid: uid,
		Rid: rid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("uid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}

func UserGetRole(c *gin.Context) {
	uid := c.Query("uid")

	var roles []models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id= user_roles.id").
		Where("user_roles_uid = ?", uid).
		Find(&roles).Debug()
	c.JSON(200, gin.H{
		"code": 200,
		"data": roles,
		"msg":  "ok",
	})
	return
}

func UsersList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var users []models.User
	redis_list_page_key := "list_page_" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_page_key).Result()
	if cacheJson == "" {
		fmt.Println("111")
		models.DB.Offset(offset).Limit(size).Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_list_page_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &users)
	}
	var total int64
	models.DB.Model(&models.User{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"data":  users,
		"total": total,
		"msg":   "查询成功",
	})
	return
}
